import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import '../utils/sputil.dart';
import '../model/_models_db.dart';

Future<TokenModel> api_login(context, String username, String password) async {
  TokenModel result = TokenModel.empty();
  try {
    final response = await http.post(
      Uri.parse('https://rtc.jxt.elef.top:8086/user/token'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(
          <String, String>{'username': username, 'password': password}),
    );

    print(response.statusCode);

    if (response.statusCode == 200) {
      //print(response.body);

      final item = json.decode(new Utf8Decoder().convert(response.bodyBytes));
      result = TokenModel.fromJson(item);

      var spu = SpUtil();
      spu.setString("token", result.token);
      spu.setString("username", result.username);
      spu.setString("name", result.name);

      //print(spu.get<String>("token"));
    } else {}
  } catch (e) {
    print(e);
  }
  return result;
}


class UserProvider with ChangeNotifier {
  TokenModel user = TokenModel.empty();
  bool loading = false;

  bool get authed => user.authed;

  Login(context, String username, String password) async {
    loading = true;
    user = await api_login(context, username, password);
    loading = false;

    notifyListeners();
  }
}
